<template>
  <view class="container">
    <view class="avatar-section">
      <view class="avatar-wrapper" @click="chooseAvatar">
        <image class="avatar" :src="userInfo.avatar || '/static/default-avatar.png'" mode="aspectFill"></image>
        <view class="avatar-edit">
          <u-icon name="camera-fill" color="#ffffff" size="44"></u-icon>
        </view>
      </view>
      <text class="avatar-tip">点击更换头像</text>
    </view>
    
    <view class="form-section">
      <u-form :model="userInfo" :rules="rules" ref="uForm" label-position="left" label-width="160">
        <u-form-item label="昵称" prop="nickname">
          <u-input v-model="userInfo.nickname" placeholder="请输入昵称" />
        </u-form-item>
        
        <u-form-item label="性别">
          <u-radio-group v-model="userInfo.gender">
            <u-radio label="男" name="male"></u-radio>
            <u-radio label="女" name="female"></u-radio>
            <u-radio label="保密" name="secret"></u-radio>
          </u-radio-group>
        </u-form-item>
        
        <u-form-item label="生日">
          <view class="date-picker" @click="showDatePicker = true">
            <text>{{ userInfo.birthday || '请选择生日' }}</text>
            <u-icon name="arrow-right" color="#c8c9cc" size="28"></u-icon>
          </view>
        </u-form-item>
        
        <u-form-item label="个人签名">
          <u-input v-model="userInfo.signature" type="textarea" placeholder="介绍一下自己吧" />
        </u-form-item>
        
        <u-form-item label="手机号码" prop="phone">
          <u-input v-model="userInfo.phone" placeholder="请输入手机号码" />
        </u-form-item>
        
        <u-form-item label="邮箱" prop="email">
          <u-input v-model="userInfo.email" placeholder="请输入邮箱" />
        </u-form-item>
      </u-form>
    </view>
    
    <view class="button-section">
      <u-button type="primary" @click="submitForm">保存修改</u-button>
    </view>
    
    <!-- 日期选择器 -->
    <u-picker
      :show="showDatePicker"
      mode="date"
      :params="dateParams"
      @confirm="onDateConfirm"
      @cancel="showDatePicker = false"
    ></u-picker>
  </view>
</template>

<script>
export default {
  data() {
    return {
      userInfo: {
        avatar: '',
        nickname: '',
        gender: 'secret',
        birthday: '',
        signature: '',
        phone: '',
        email: ''
      },
      showDatePicker: false,
      dateParams: {
        year: {
          start: 1970,
          end: new Date().getFullYear()
        },
        month: {
          start: 1,
          end: 12
        },
        day: {
          start: 1,
          end: 31
        }
      },
      rules: {
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 20, message: '昵称长度在2-20个字符之间', trigger: 'blur' }
        ],
        phone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      }
    }
  },
  onLoad() {
    this.loadUserInfo()
  },
  methods: {
    // 加载用户信息
    loadUserInfo() {
      try {
        const userInfoStr = uni.getStorageSync('userInfo')
        if (userInfoStr) {
          const userInfo = JSON.parse(userInfoStr)
          this.userInfo = {
            ...this.userInfo,
            ...userInfo
          }
        }
      } catch (error) {
        console.error('加载用户信息失败', error)
      }
      
      // 在实际应用中，这里应该从后端API获取用户信息
      // this.getUserInfoFromApi()
    },
    
    // 从API获取用户信息
    getUserInfoFromApi() {
      uni.showLoading({
        title: '加载中...'
      })
      
      // 模拟API请求
      setTimeout(() => {
        uni.hideLoading()
        
        // 模拟数据
        this.userInfo = {
          avatar: '/static/avatar.jpg',
          nickname: '测试用户',
          gender: 'male',
          birthday: '1990-01-01',
          signature: '这是一个测试签名',
          phone: '13800138000',
          email: 'test@example.com'
        }
      }, 1000)
    },
    
    // 选择头像
    chooseAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          // 获取选择的图片临时路径
          const tempFilePath = res.tempFilePaths[0]
          
          // 在实际应用中，这里应该上传图片到服务器
          // this.uploadAvatar(tempFilePath)
          
          // 临时直接使用本地路径
          this.userInfo.avatar = tempFilePath
        }
      })
    },
    
    // 上传头像到服务器
    uploadAvatar(filePath) {
      uni.showLoading({
        title: '上传中...'
      })
      
      // 模拟上传
      setTimeout(() => {
        uni.hideLoading()
        
        // 设置上传后的头像URL（实际应用中应该是服务器返回的URL）
        this.userInfo.avatar = filePath
        
        uni.showToast({
          title: '上传成功',
          icon: 'success'
        })
      }, 1000)
    },
    
    // 日期确认
    onDateConfirm(e) {
      this.showDatePicker = false
      const { year, month, day } = e.value
      // 格式化日期为 YYYY-MM-DD
      const formattedMonth = month < 10 ? `0${month}` : month
      const formattedDay = day < 10 ? `0${day}` : day
      this.userInfo.birthday = `${year}-${formattedMonth}-${formattedDay}`
    },
    
    // 提交表单
    submitForm() {
      this.$refs.uForm.validate(valid => {
        if (valid) {
          uni.showLoading({
            title: '保存中...'
          })
          
          // 在实际应用中，这里应该调用API保存用户信息
          // this.saveUserInfoToApi()
          
          // 临时保存到本地存储
          try {
            uni.setStorageSync('userInfo', JSON.stringify(this.userInfo))
            
            setTimeout(() => {
              uni.hideLoading()
              uni.showToast({
                title: '保存成功',
                icon: 'success',
                success: () => {
                  // 延迟返回上一页
                  setTimeout(() => {
                    uni.navigateBack()
                  }, 1500)
                }
              })
            }, 1000)
          } catch (error) {
            uni.hideLoading()
            uni.showToast({
              title: '保存失败',
              icon: 'none'
            })
          }
        }
      })
    },
    
    // 保存用户信息到API
    saveUserInfoToApi() {
      // 模拟API请求
      setTimeout(() => {
        uni.hideLoading()
        
        uni.showToast({
          title: '保存成功',
          icon: 'success',
          success: () => {
            // 延迟返回上一页
            setTimeout(() => {
              uni.navigateBack()
            }, 1500)
          }
        })
      }, 1000)
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 40rpx;
}

.avatar-wrapper {
  position: relative;
  width: 160rpx;
  height: 160rpx;
  border-radius: 50%;
  overflow: hidden;
  margin-bottom: 20rpx;
}

.avatar {
  width: 100%;
  height: 100%;
}

.avatar-edit {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60rpx;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-tip {
  font-size: 24rpx;
  color: #999;
}

.form-section {
  margin-bottom: 40rpx;
}

.date-picker {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 70rpx;
  font-size: 28rpx;
  color: #333;
}

.button-section {
  padding: 20rpx 0;
}
</style> 